/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.escom.healthlc.utils;

import com.escom.healthlc.entidad.MedicoVO;
import com.escom.healthlc.entidad.PacienteVO;
import java.lang.reflect.Field;
import java.util.Comparator;
import org.primefaces.model.SortOrder;

/**
 *
 * @author Carlos
 */
public class LazySorterMngMedico implements Comparator<MedicoVO> {

    private String sortField;

    private SortOrder sortOrder;

    public LazySorterMngMedico(String sortField, SortOrder sortOrder) {
        this.sortField = sortField;
        this.sortOrder = sortOrder;
    }

    @Override
    public int compare(MedicoVO medico1, MedicoVO medico2) {
        try {
            Object value1;
            Object value2;
            Field field1;
            Field field2;
            String compere = sortField;

            
            if (compere.equals("nombre") || compere.equals("apPaterno")) {
                field1 = medico1.getClass().getSuperclass().getDeclaredField(sortField);
                field2 = medico2.getClass().getSuperclass().getDeclaredField(sortField);
                field1.setAccessible(true);
                field2.setAccessible(true);
                value1 = field1.get(medico1);
                value2 = field2.get(medico2);
            } else {
                field1 = medico1.getClass().getDeclaredField(sortField);
                field2 = medico2.getClass().getDeclaredField(sortField);
                field1.setAccessible(true);
                field2.setAccessible(true);
                value1 = field1.get(medico1);
                value2 = field2.get(medico2);
            }

            int value = ((Comparable) value1).compareTo(value2);

            return SortOrder.ASCENDING.equals(sortOrder) ? value : -1 * value;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }
}
